﻿using VMExplorer.Win32;

namespace VMExplorer.MemoryObjects
{
  class MemoryObjectStats
  {
    #region Private fields

    private IMemoryObject _mo = null;
    private uint _commitedBytes = 0;
    private uint _reservedBytes = 0;
    private uint _totalBytes = 0;
    private uint _fragments = 0;
    private bool _upToDate = false;

    #endregion
    #region Construction
    
    public MemoryObjectStats (IMemoryObject mo)
    {
      _mo = mo;
    }

    #endregion
    #region Update statistics

    private void UpdateStatistics ()
    {
      if (!_upToDate)
      {
        _upToDate = true;
        _commitedBytes = 0;
        _reservedBytes = 0;
        _totalBytes = 0;
        _fragments = 0;

        foreach (RegionInfo ri in _mo.Ranges)
        {
          switch (ri.State)
          {
            case Native.PAGE_STATE.MEM_COMMIT:
              _totalBytes += ri.Size;
              _commitedBytes += ri.Size;
              _fragments++;
              break;

            case Native.PAGE_STATE.MEM_RESERVE:
              _totalBytes += ri.Size;
              _reservedBytes += ri.Size;
              break;
          }
        }
      }
    }

    #endregion
    #region Public properties

    public uint CommittedBytes { get { UpdateStatistics (); return _commitedBytes; } }
    public uint ReservedBytes { get { UpdateStatistics (); return _reservedBytes; } }
    public uint TotalBytes { get { UpdateStatistics (); return _totalBytes; } }
    public uint Fragments { get { UpdateStatistics (); return _fragments; } }

    #endregion
  }
}
